import { Provide } from '@midwayjs/decorator';
import { InjectEntityModel } from '@midwayjs/orm';
import { loeeBaseService } from '../../../comservice/loeeBaseService';
import { Repository } from 'typeorm';
import { classgroupEntity } from '../entity/classgroup';
import { classgroupStudentsEntity } from '../../classgroupStudents/entity/classgroupStudents';
import { studentEntity } from '../../student/entity/student';
import { CourseTypeEntity } from '../../courseType/entity/courseType';


/**
 * 描述
 */
@Provide()
export class ClassGroupService extends loeeBaseService {

  @InjectEntityModel(classgroupEntity)
  classgroupEntity: Repository<classgroupEntity>;

  @InjectEntityModel(classgroupStudentsEntity)
  classgroupStudentsEntity: Repository<classgroupStudentsEntity>;

  @InjectEntityModel(studentEntity)
  studentEntity: Repository<studentEntity>;

  @InjectEntityModel(CourseTypeEntity)
  CourseTypeEntity: Repository<CourseTypeEntity>;


  /**
   * 重写删除方法设置为逻辑删除
   */
   async delete(ids:any) {

    await super.delete(ids)
    let idsArray: Array<number> 
    if (ids instanceof Array) {
      idsArray = ids
    }else{
      idsArray = ids.split(",")
    }
    for (let id of idsArray) {
      await this.classgroupStudentsEntity.delete({classgroup_id:id});
    }
    await this.modifyAfter(ids,'delete');
  }
  
  /**
   * 重写新增接口
   */
  public async add(param: any) {
    console.log(param, '22222222222');
    // student_id
    // classgroup_id
    const classgroupObj: any = await super.add(param);

    if (param.class_students.length !== 0) {
      for (let i of param.class_students) {
        await this.classgroupStudentsEntity.save({ student_id: parseInt(i), classgroup_id: classgroupObj.id })
        console.log('------------');

      }
    }
    return {
      id: param.id
    };
  }

  /**
   * 重写分页查询
   * @param query
   */
  async page(query) {
    const { keyWord, class_number, class_date, class_course_type, class_type, class_teacher, class_class_classroom, student_id } = query;
    // const permsDepartmentArr = await this.baseSysPermsService.departmentIds(
    //   this.ctx.admin.userId
    // ); // 部门权限
    const sql = `
        SELECT
            a.id,a.class_course_type,a.class_date,a.class_type,a.start_date,a.end_date,a.class_name,a.class_number,a.class_teacher,a.class_class_classroom,a.class_level,a.class_week,a.class_start_time,a.class_end_time,a.note,a.createTime,a.updateTime,a.isDelete,
            GROUP_CONCAT(c.name) AS class_students
        FROM
            classgroup a
            LEFT JOIN classgroup_students b ON a.id = b.classgroup_id
            LEFT JOIN student c ON b.student_id = c.id
        WHERE 1 = 1 and
        a.isDelete = false
        ${this.setSql(class_number, 'and a.class_number = ?', [class_number])}
        ${this.setSql(class_date, 'and a.class_date = ?', [class_date])}
        ${this.setSql(class_course_type, 'and a.class_course_type = ?', [class_course_type])}
        ${this.setSql(class_type, 'and a.class_type = ?', [class_type])}
        ${this.setSql(class_teacher, 'and a.class_teacher = ?', [class_teacher])}
        ${this.setSql(class_class_classroom, 'and a.class_class_classroom = ?', [class_class_classroom])}
        ${this.setSql(student_id, 'and b.student_id = ? or b.student_id = ?', [student_id, ""])}

        
        ${this.setSql(keyWord, 'and (a.class_name LIKE ? or a.class_date LIKE ?)', [
      `%${keyWord}%`,
      `%${keyWord}%`,
    ])}
        GROUP BY a.id
        `;
    return this.sqlRenderPage(sql, query);
  }

  /**
   * 根据ID获得信息
   * @param id
   */
  public async info(id: any) {
    // console.log(id,'--start----');

    // const info: any = await this.classgroupEntity.findOne({ id });
    const info:any = await this.classgroupEntity.createQueryBuilder("a")
      .leftJoinAndSelect(CourseTypeEntity, 'b', 'a.class_course_type = b.id')
      .leftJoinAndSelect(classgroupStudentsEntity, 'c', 'a.id = c.classgroup_id')
      .leftJoinAndSelect(studentEntity, 'e', 'c.student_id = e.id')
      .select(`
        a.id as id,
        class_course_type,
        class_date,
        class_type,
        start_date,
        end_date,
        class_name,
        class_number,
        class_teacher,
        class_class_classroom,
        class_level,
        class_week,
        class_start_time,
        class_end_time,
        a.note as note,
        b.course_name as course_name,
        group_concat(e.name)
      `)
      .where("a.id = :id", { id:id })
      .groupBy("a.id")
      .getRawMany();
    console.log(info,'--start----');
    

    const studentId = await this.nativeQuery(
      'select student_id from classgroup_students where classgroup_id = ?',
      [id]
    );

    const info1 =  await this.nativeQuery(
      `
      select a.id as id, a.class_course_type, a.class_date, a.class_type,start_date, a.end_date, a.class_name, a.class_number, a.class_teacher, a.class_class_classroom, a.class_level, a.class_week, a.class_start_time, a.class_end_time,a.note as note,b.course_name as course_name,c.studentName,c.class_students,d.name as classroom,e.name as teacherName
      from classgroup a
      left join course_type b on a.class_course_type = b.id
      left join (select a.classgroup_id,group_concat(b.name) as studentName,group_concat(b.id) as class_students from classgroup_students a 
      left join student b on a.student_id = b.id
      group by a.classgroup_id) c on a.id = c.classgroup_id 
      left join classroom d on a.class_class_classroom = d.id
      left join teacher e on a.class_teacher = e.id
      where a.id = ${id}
      `
    )
    
    
    let studentName = []

    for (let i of studentId) {
      const student =  await this.nativeQuery(
        'select name from student where id = ?',
        [parseInt(i.student_id)]
      )
      studentName.push(student[0].name)
    }



    // console.log(studentId,'--start----');

    if (info) {
      if (studentId) {
        info.class_students = studentId.map(e => {
          return parseInt(e.student_id);
        });
        info.studentName = studentName
      }
    }
    return info1[0];
  }

  /**
     * 修改
     * @param param 数据
     */
  async update(param) {
    await super.update(param);

    this.updateClassStudents(param)
    // console.log(param.class_students,'11111122121');

    // if (param.class_students.length !== 0) {
    //   for (let i of param.class_students) {
    //     await this.classgroupStudentsEntity.save({ student_id: parseInt(i), classgroup_id: classgroupObj.id })
    //     console.log('------------');

    //   }
    // }
  }

  /**
   * 更新班级学生信息
   * @param user
   */
  async updateClassStudents(params: any) {
    await this.classgroupStudentsEntity.delete({ classgroup_id: params.id });
    if (params.class_students) {
      for (const i of params.class_students) {
        await this.classgroupStudentsEntity.save({ student_id: parseInt(i), classgroup_id: params.id });
      }
    }
  }
}